
const fs = require('fs');

const queryAI = require("./query.js");

// 读取指定目录下的所有.cs文件
const path = require('path');
var directoryPath = 'C:\\Users\\augur_chenbiao\\source\\repos\\TilesetGEA\\TilesetGEA';

const AllFiles = [];

const waitList = []
function appendWaitList(dir) {
    waitList.push({ dir: dir, fileNames: [] });
    console.log(waitList.length, "waitList. append")
}
function appendWaitListOfFiles(dir, fileName) {
    for (var i = 0; i < waitList.length; i++) {
        var wl = waitList[i]
        if (wl.dir == dir) {
            wl.fileNames.push(fileName);
            break;
        }
    }
}
function removeWaitList(dir) {
    for (var i = 0; i < waitList.length; i++) {
        if (waitList[i].dir == dir) {
            waitList.splice(i, 1);
            break;
        }
    }
    console.log(waitList.length, "waitList remove")
    if (waitList.length == 0) {
        console.log(AllFiles.length)
        for(var j=0;j<AllFiles.length;j++)
            console.log(AllFiles[j].fileName)
        analysisByAI();
    }
}
function removeWaitListOfFiles(dir, fileName,sign) {
    for (var i = 0; i < waitList.length; i++) {
        var wl = waitList[i]
        if (wl.dir == dir) {
            let notFind=true;
            for (var j = 0; j <wl.fileNames.length; j++) {
                if (wl.fileNames[j] == fileName) {
                    wl.fileNames.splice(j, 1);
                    notFind=false;
                    break;
                }
            }
            if (notFind){
                console.log("notFind", wl.fileNames, fileName, sign)
            }
            if (wl.fileNames.length == 0) {
                removeWaitList(wl.dir);
            }
            break;
        }
    }
}

function readAllFiles(onFinish) {

    function readDirectory(dirPath) {
        appendWaitList(dirPath);

        fs.readdir(dirPath, (err, files) => {
            if (err) {
                console.error('读取目录时出错:', err);
                removeWaitList(dirPath);
                return;
            }

            let pendingFiles = files.length;
            if (pendingFiles === 0) {
                removeWaitList(dirPath);
                return;
            }
            
            files.forEach(file => {
                const filePath = path.join(dirPath, file);
                appendWaitListOfFiles(dirPath, file)
                fs.stat(filePath, (err, stats) => {
                    if (err) {
                        console.error(`获取文件信息时出错: ${filePath}`, err);
                        removeWaitListOfFiles(dirPath, file,"f1")
                        return;
                    }

                    if (stats.isDirectory()) {
                        readDirectory(filePath);
                        removeWaitListOfFiles(dirPath, file,"f2")
                    } else if (path.extname(file) === '.cs') {
                        if (file.indexOf(".NETStandard,Version")>=0){
                            removeWaitListOfFiles(dirPath, file, "f2")
                            return;
                        }
                        if (file.indexOf("AssemblyInfo.cs") >= 0) {
                            removeWaitListOfFiles(dirPath, file, "f2")
                            return;
                        }
                        if (file.indexOf(".Designer.cs") >= 0) {
                            removeWaitListOfFiles(dirPath, file, "f2")
                            return;
                        }
                        if (file.indexOf("AssemblyAttributes.cs") >= 0) {
                            removeWaitListOfFiles(dirPath, file, "f2")
                            return;
                        }
                        fs.readFile(filePath, 'utf8', (err, data) => {
                            if (err) {
                                console.error(`读取文件 ${file} 时出错:`, err);
                                removeWaitListOfFiles(dirPath, file, "f3")
                                return;
                            }
                            AllFiles.push({
                                fileName: file,
                                fullPath: filePath,
                                fileContent: data
                            });
                            removeWaitListOfFiles(dirPath, file, "f4")
                        });
                    }
                    else{
                        removeWaitListOfFiles(dirPath, file, "f5")
                    }
                });

            });
        });
    }

    readDirectory(directoryPath);
}

async function analysisByAI() {
    console.log("11", AllFiles.length)

    // 创建存储所有文件信息的数组
    const fileInfoArray = [];

    for (var i = 0; i < AllFiles.length; i++) {
        let fileInfo = AllFiles[i];
        var t = await queryAI(fileInfo.fileContent,"代码结构分析");
        // 写入AI分析结果
        fs.writeFile('assets/codeStruct/output_' + fileInfo.fileName + ".txt", t, (err) => {
            if (err) {
                console.error('写入文件时出错:', err);
                return;
            }
            console.log('文件写入成功:代码结构分析' + fileInfo.fileName);
        });
        var t2 = await queryAI(fileInfo.fileContent,"知识图谱分析");
        // 写入AI分析结果
        fs.writeFile('assets/codeStruct/kn_' + fileInfo.fileName + ".json", t2, (err) => {
            if (err) {
                console.error('写入文件时出错:', err);
                return;
            }
            console.log('文件写入成功:知识图谱分析' + fileInfo.fileName);
        });
        var t3 = await queryAI(fileInfo.fileContent, "代码质量打分");
        // 写入AI分析结果
        fs.writeFile('assets/codeStruct/sc' + fileInfo.fileName + ".json", t3, (err) => {
            if (err) {
                console.error('写入文件时出错:', err);
                return;
            }
            console.log('文件写入成功:代码质量打分' + fileInfo.fileName);
        });

        // 收集文件信息
        fileInfoArray.push({
            fileName: AllFiles[i].fileName,
            fullPath: AllFiles[i].fullPath,
            fileContent: AllFiles[i].fileContent
        });
    }

    // 将文件信息写入index.json
    fs.writeFile('assets/codeStruct/index.json', JSON.stringify(fileInfoArray, null, 2), (err) => {
        if (err) {
            console.error('写入index.json时出错:', err);
            return;
        }
        console.log('index.json写入成功');
    });
}
function run(_directoryPath) {
    directoryPath = _directoryPath;
    readAllFiles();
}

module.exports = run